package com.ypf.rpc.nettyHandler;

import com.ypf.rpc.manager.client.RpcClientManager;
import com.ypf.rpc.message.RpcQueryRegisterResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise;

import java.net.InetSocketAddress;

@ChannelHandler.Sharable
public class RpcQueryRegisterResponseMessageHandler extends SimpleChannelInboundHandler<RpcQueryRegisterResponseMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcQueryRegisterResponseMessage message) throws Exception {
        System.out.println("被选中的服务ip为:"+message.getServerHost()+" 被选中的端口号为:"+message.getServerPort());

        try {
            int sequenceId = message.getSequenceId();

            Promise<Object> promise = RpcClientManager.queryRegisterPROMISES.get(sequenceId);

            if (promise!=null){
                if (message.getServerHost()!=null&&message.getServerPort()!=null){
                    InetSocketAddress inetSocketAddress = new InetSocketAddress(message.getServerHost(),message.getServerPort());
                    promise.setSuccess(inetSocketAddress);
                }else {
                    promise.setFailure(new RuntimeException("查询服务不存在"));
                }
            }else {
                promise.setFailure(new Exception("promise不存在"));
            }


        }finally {
            ReferenceCountUtil.release(message);   // 释放掉message
        }

    }
}
